using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using DALTMClient.WSDL;

namespace DALTMClient
{
    public partial class frmAluMain : Form
    {
        #region Variable
        const string Title = "Chat Client !";
        public static bool CheckAdd;
        public static string UserName = "";
        public static string TitleFormMess;
        public static bool state;
        AluMessenger Chat = new AluMessenger();
        public static ArrayList ListChat = new ArrayList();
        public static ArrayList ListFriend = new ArrayList();
        #endregion

        #region frmAluMain
        public frmAluMain()
        {
            InitializeComponent();
        }
        #endregion

        #region Init
        private void Init()
        {
            #region Variable
            picSignIn.Image = DALTMClient.Properties.Resources.PIKACHU;
            mnuSignOut.Visible = false;
            mnuActions.Visible = false;
            mnuContact.Visible = false;
            mnuMyAccount.Visible = false;
            mnuMyContact.Visible = false;
            mnuMyDisplay.Visible = false;
            mnuSpa1.Visible = false;
            panelBottom.Visible = false;
            panelList.Visible = false;
            panelTop.Visible = false;
            panelSignIn.Visible = true;
            btnCancel.Visible = false;
            lblInvisible.Visible = false;
            lblSignIn.Visible = false;
            txtPassWord.Visible = true;
            txtUserName.Visible = true;
            chkAutomatic.Visible = true;
            chkInvisible.Visible = true;
            chkRemember.Visible = true;
            btnSignIn.Visible = true;
            linkForgotPass.Visible = true;
            label2.Visible = true;
            label3.Visible = true;
            linkGetNewAccount.Visible = true;
            #endregion
        }
        #endregion

        #region Login
        private void Login()
        {
            mnuSignOut.Visible = true;
            mnuActions.Visible = true;
            mnuContact.Visible = true;
            panelBottom.Visible = true;
            panelList.Visible = true;
            panelTop.Visible = true;
            panelSignIn.Visible = false;
            mnuMyAccount.Visible = true;
            mnuMyContact.Visible = true;
            mnuMyDisplay.Visible = true;
            mnuSpa1.Visible = true;

            lblUserName.Text = UserName;
            if (chkInvisible.Checked)
            {
                myStatus.Image = DALTMClient.Properties.Resources.offline;
                mnuInvisible.Enabled = false;
                mnuAvailable.Enabled = true;
                state = false;
            }
            else
            {
                myStatus.Image = DALTMClient.Properties.Resources.online;
                mnuInvisible.Enabled = true;
                mnuAvailable.Enabled = false;
                state = true;
            }
        }
        #endregion

        #region txtSearchNickName_MouseClick
        private void txtSearchNickName_MouseClick(object sender, MouseEventArgs e)
        {
            txtSearchNickName.Text = "";
            txtSearchNickName.ForeColor = Color.Black;
            txtSearchNickName.Font = new Font("Microsoft Sans Serif", 10, FontStyle.Bold);
        }
        #endregion

        #region txtSearchNickName_MouseLeave
        private void txtSearchNickName_MouseLeave(object sender, EventArgs e)
        {
            txtSearchNickName.ForeColor = Color.Silver;
            txtSearchNickName.Font = new Font("Microsoft Sans Serif", 10, FontStyle.Regular);
            txtSearchNickName.Text = "Type some contact information...";
        }
        #endregion

        #region LoadListFriend
        private void LoadListFriend()
        {
            ListFriend.Clear();
            DataTable dt = Chat.ListFriends(UserName);
            if (dt.Rows.Count > 0)
            {
                tvwListFriend.Nodes.Add(dt.Rows[0][0].ToString(), dt.Rows[0][0].ToString(), 3, 3);
                ListFriend.Add(dt.Rows[0][1].ToString());
                for (int i = 1; i < dt.Rows.Count; i++)
                {
                    ListFriend.Add(dt.Rows[i][1].ToString());
                    if (dt.Rows[i][0].ToString() != dt.Rows[i - 1][0].ToString())
                        tvwListFriend.Nodes.Add(dt.Rows[i][0].ToString(), dt.Rows[i][0].ToString(), 3, 3);

                }

                foreach (TreeNode node in tvwListFriend.Nodes)
                {
                    node.NodeFont = new Font("Tahoma", 11, FontStyle.Bold);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (node.Text.Equals(dt.Rows[i][0]))
                        {
                            if (dt.Rows[i][2].ToString().Trim() == "True" && dt.Rows[i][3].ToString().StartsWith("Online"))
                                tvwListFriend.Nodes[node.Index].Nodes.Add(dt.Rows[i][1].ToString(), dt.Rows[i][1].ToString(), 1, 1);
                            else
                                tvwListFriend.Nodes[node.Index].Nodes.Add(dt.Rows[i][1].ToString(), dt.Rows[i][1].ToString(), 0, 0);
                        }
                    }
                }
                tvwListFriend.ExpandAll();
            }
        }
        #endregion

        #region SignIning
        private bool SignIning()
        {
            bool ok = false;
            if (Chat.IsExistsUserName(txtUserName.Text))
            {
                if (MD5Hash.Verify(txtPassWord.Text, Chat.GetPasswordHash(txtUserName.Text)))
                {
                    UserName = txtUserName.Text;
                    if (chkInvisible.Checked)
                        Chat.UpdateState(UserName, "Online", '0');
                    else Chat.UpdateState(UserName, "Online", '1');
                    ok = true;
                    timerUpdateSV.Enabled = true;
                }
                else
                {
                    ListFriend.Clear();
                    ListChat.Clear();
                    tvwListFriend.Nodes.Clear();
                    state = false;
                    timerListener.Stop();
                    timerListener.Enabled = false;
                    timerGetMyAvatar.Stop();
                    timerGetMyAvatar.Enabled = false;
                    UserName = "";
                    timerUpdateSV.Enabled = false;
                    Init();
                    MessageBox.Show("Please check username and password then try again!", "Alu! Messenger !");
                }
            }
            else
                MessageBox.Show("Please check username and password then try again!", "Alu! Messenger!");
            return ok;
        }
        #endregion

        #region btnSignIn_Click
        private void btnSignIn_Click(object sender, EventArgs e)
        {
            //try
            //{
            if (txtUserName.Text != "")
            {
                picSignIn.Image = DALTMClient.Properties.Resources.PIKACHU;
                btnCancel.Visible = true;
                if (chkInvisible.Checked)
                    lblInvisible.Visible = true;
                lblSignIn.Visible = true;
                lblSignIn.Text = "Signing is as\n" + txtUserName.Text;
                txtPassWord.Visible = false;
                txtUserName.Visible = false;
                chkAutomatic.Visible = false;
                chkInvisible.Visible = false;
                chkRemember.Visible = false;
                btnSignIn.Visible = false;
                linkForgotPass.Visible = false;
                label2.Visible = false;
                label3.Visible = false;
                linkGetNewAccount.Visible = false;
                timerWait.Start();
            }
            else
                MessageBox.Show("Please enter your username !", Title);
            //}
            //catch {            }
        }
        #endregion

        #region btnAddContact_Click
        private void btnAddContact_Click(object sender, EventArgs e)
        {
            using (frmAddFriend frm = new frmAddFriend())
            {
                frm.ShowDialog();
            }
            if (CheckAdd)
            {
                tvwListFriend.Nodes.Clear();
                LoadListFriend();
                CheckAdd = false;
            }
        }
        #endregion

        #region frmGlobalChat_Load
        private void frmGlobalChat_Load(object sender, EventArgs e)
        {
            Init();
        }
        #endregion

        #region linkGetNewAccount_LinkClicked
        private void linkGetNewAccount_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            using (frmCreateAccount frmCreateAccount = new frmCreateAccount())
            {
                frmCreateAccount.ShowDialog();
            }
        }
        #endregion

        #region mnuSignOut_Click
        private void mnuSignOut_Click(object sender, EventArgs e)
        {
            try
            {
                Chat.UpdatePulse(UserName);
                ListFriend.Clear();
                ListChat.Clear();
                tvwListFriend.Nodes.Clear();
                state = false;
                timerListener.Stop();
                timerListener.Enabled = false;
                timerGetMyAvatar.Stop();
                timerGetMyAvatar.Enabled = false;
                Chat.UpdateState(UserName, "Offline", '1');
                timerUpdateSV.Enabled = false;
                UserName = "";
                Init();
                if (!chkRemember.Checked)
                {
                    txtPassWord.Text = "";
                    txtUserName.Text = "";
                }
            }
            catch { }
        }
        #endregion

        #region tvwListFriend_NodeMouseClick
        private void tvwListFriend_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Level == 0)
                if (e.Node.IsExpanded)
                {
                    e.Node.SelectedImageIndex = 3;
                    e.Node.ImageIndex = 3;
                }
                else
                {
                    e.Node.SelectedImageIndex = 2;
                    e.Node.ImageIndex = 2;
                }
            if (e.Button == MouseButtons.Right)
                tvwListFriend.ContextMenuStrip = contextMenuRemove;
            else tvwListFriend.ContextMenuStrip = null;
        }
        #endregion

        #region tvwListFriend_NodeMouseDoubleClick
        private void tvwListFriend_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Level == 1)
            {
                TitleFormMess = String.Format("{0} send message to {1}", UserName, e.Node.Text);
                ListChat.Add(e.Node.Text);
                try
                {
                    frmSendMessenger frm = new frmSendMessenger();
                    frm.Show();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
        }
        #endregion

        #region txtSearchNickName_TextChanged
        private void txtSearchNickName_TextChanged(object sender, EventArgs e)
        {
            bool ok = false;

            foreach (TreeNode tn in tvwListFriend.Nodes)
            {
                foreach (TreeNode subtn in tn.Nodes)
                    if (subtn.BackColor == Color.Blue)
                    {
                        subtn.BackColor = Color.White;
                        subtn.ForeColor = Color.Black;
                        ok = true;
                    }
                if (ok) break;
            }
            ok = false;
            foreach (TreeNode tn in tvwListFriend.Nodes)
            {
                foreach (TreeNode subtn in tn.Nodes)
                    if (txtSearchNickName.Text.Length > 0 && subtn.Text.Contains(txtSearchNickName.Text))
                    {
                        subtn.BackColor = Color.Blue;
                        subtn.ForeColor = Color.White;
                        ok = true;
                    }
                if (ok) break;
            }
        }
        #endregion

        #region timerListener_Tick
        private void timerListener_Tick(object sender, EventArgs e)
        {
            try
            {
                timerListener.Interval = 1000;
                Chat.UpdatePulseByUserId(UserName);
                object[] list = Chat.ListFriendsShowOnline(UserName);
                object[] list2 = Chat.ListFriendsOnline(UserName);
                ArrayList listFriendShowOnline = new ArrayList();
                ArrayList listFriendOnline = new ArrayList();
                listFriendShowOnline.AddRange(list);
                listFriendOnline.AddRange(list2);

                foreach (TreeNode node in tvwListFriend.Nodes)
                    foreach (TreeNode nd in node.Nodes)
                    {
                        if (listFriendShowOnline.Contains(nd.Text))
                        {
                            if (nd.ImageIndex != 1)
                            {
                                nd.ImageIndex = 1;
                                nd.SelectedImageIndex = 1;
                            }
                        }
                        else
                        {
                            if (nd.ImageIndex != 0)
                            {
                                nd.ImageIndex = 0;
                                nd.SelectedImageIndex = 0;
                            }
                        }
                        if (listFriendOnline.Contains(nd.Text))
                        {
                            string kt = Chat.IsExistsMessOnline(UserName);
                            if (kt == nd.Text)
                                if (!ListChat.Contains(kt))
                                {
                                    TitleFormMess = String.Format("{0} send message to {1}", UserName, kt);
                                    ListChat.Add(kt);
                                    frmSendMessenger frm = new frmSendMessenger();
                                    frm.Show();
                                }
                        }
                    }
                timerListener.Enabled = true;
            }
            catch { }
        }
        #endregion

        #region mnuAvailable_Click
        private void mnuAvailable_Click(object sender, EventArgs e)
        {
            try
            {
                Chat.UpdateState(UserName, "Online", '1');
                mnuAvailable.Enabled = false;
                mnuInvisible.Enabled = true;
                state = true;
                myStatus.Image = DALTMClient.Properties.Resources.online;
            }
            catch            {            }
        }
        #endregion

        #region mnuInvisible_Click
        private void mnuInvisible_Click(object sender, EventArgs e)
        {
            try
            {
                Chat.UpdateState(UserName, "Online", '0');
                mnuAvailable.Enabled = true;
                mnuInvisible.Enabled = false;
                state = false;
                myStatus.Image = DALTMClient.Properties.Resources.offline;
            }
            catch { }
        }
        #endregion

        #region timerWait_Tick
        private void timerWait_Tick(object sender, EventArgs e)
        {
            //try
            //{
            timerWait.Stop();
            timerWait.Interval = 5000;
            if (SignIning())
            {
                Login();
                if (File.Exists(String.Format("{0}\\Profiles\\{1}.gif", Application.StartupPath, frmAluMain.UserName)))
                    myPicture.Image = Image.FromFile(String.Format("{0}\\Profiles\\{1}.gif", Application.StartupPath, frmAluMain.UserName));
                LoadListFriend();
                if (Chat.ReceiveMessageOffline(UserName).Rows.Count > 0)
                {
                    frmReceiveMessOffline frm = new frmReceiveMessOffline();
                    frm.Show();
                }

                timerListener.Start();
                timerGetMyAvatar.Start();
                timerWait.Enabled = false;
            }
            //}
            //catch           {            }
        }
        #endregion

        #region btnCancel_Click
        private void btnCancel_Click(object sender, EventArgs e)
        {
            timerWait.Enabled = false;
            Init();
        }
        #endregion

        #region timerGetMyAvatar_Tick
        private void timerGetMyAvatar_Tick(object sender, EventArgs e)
        {
            try
            {
                timerGetMyAvatar.Stop();
                if (File.Exists(String.Format("{0}\\Profiles\\{1}.gif", Application.StartupPath, frmAluMain.UserName)))
                    myPicture.Image = Image.FromFile(String.Format("{0}\\Profiles\\{1}.gif", Application.StartupPath, frmAluMain.UserName));
                else myPicture.Image = DALTMClient.Properties.Resources.PhotoSmall;
                timerGetMyAvatar.Enabled = true;
            }
            catch { }
        }
        #endregion

        #region frmGlobalChat_FormClosing
        private void frmGlobalChat_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you want to close sure ?", "Alu! Messenger", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Chat.UpdateState(UserName, "Offline", '1');
                }
                else
                    e.Cancel = true;
            }
            catch { }
        }
        #endregion

        #region closeToolStripMenuItem_Click
        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }
        #endregion

        #region mnuRemove_Click
        private void mnuRemove_Click(object sender, EventArgs e)
        {
            try
            {
                if (tvwListFriend.SelectedNode != null)
                {
                    if (tvwListFriend.SelectedNode.Level == 1)
                    {
                        if (MessageBox.Show(String.Format("Are you want to remove user {0} from list friend user sure ?", tvwListFriend.SelectedNode.Text), "Alu! Messenger", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            Chat.RemoveUser(UserName, tvwListFriend.SelectedNode.Text);
                            tvwListFriend.SelectedNode.Remove();
                        }
                    }
                    else
                    {
                        if (MessageBox.Show(String.Format("Are you want to remove group {0} from list group sure ?", tvwListFriend.SelectedNode.Text), "Alu! Messenger", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            Chat.RemoveGroup(UserName, tvwListFriend.SelectedNode.Text);
                            tvwListFriend.SelectedNode.Remove();
                        }
                    }
                }
                else
                    MessageBox.Show("Please select object that you want to remove !", "Alu! Messenger");
            }
            catch
            {
            }
        }
        #endregion

        #region addAContactToolStripMenuItem_Click
        private void addAContactToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmAddFriend frm = new frmAddFriend())
            {
                frm.ShowDialog();
            }
            if (CheckAdd)
            {
                tvwListFriend.Nodes.Clear();
                LoadListFriend();
                CheckAdd = false;
            }
        }
        #endregion

        #region timerUpdate
        private void timerUpdateSV_Tick(object sender, EventArgs e)
        {
            try
            {
                if (UserName.Length > 1)
                    Chat.UpdateServerPulseForAllUser();
            }
            catch { }
        }

        private void timerUpdateClient_Tick(object sender, EventArgs e)
        {
            try
            {
                if (UserName.Length > 1)
                    Chat.UpdatePulseByUserId(UserName);
            }
            catch { }
        }
        #endregion
    }
}